using Domain;
using ErrorCode;
using MediatR;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Transactions;
using WriteAPI.Command.生产计划;
using SqlSugar;

namespace WriteAPI.CommandHandle.生产计划
{
    /// <summary>
    /// 扩展的生产计划添加命令处理程序
    /// </summary>
    public class AddProductionPlanCommandExtendedHandler : IRequestHandler<AddProductionPlanCommandExtended, APIResult<int>>
    {
        private readonly ISqlSugarClient db;
        
        public AddProductionPlanCommandExtendedHandler(ISqlSugarClient db)
        {
            this.db = db;
        }
        
        public async Task<APIResult<int>> Handle(AddProductionPlanCommandExtended request, CancellationToken cancellationToken)
        {
            var result = new APIResult<int>();
            
            // 参数验证
            if (request == null)
            {
                result.Message = "请求参数不能为空";
                return result;
            }
            
            if (string.IsNullOrWhiteSpace(request.PlanNumber))
            {
                result.Message = "计划编号不能为空";
                return result;
            }
            
            try
            {
                using (var scope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
                {

                    // 1. 生成有意义的生产计划编号
                    string prefix = "SCJH";
                    string datePart = DateTime.Now.ToString("yyyyMMdd");
                    string todayPrefix = prefix + datePart;

                    // 查询当天最大编号
                    string maxNumber = await db.Queryable<Lwp_ProductionPlan>()
                        .Where(x => x.DocNumber.StartsWith(todayPrefix))
                        .OrderBy(x => x.DocNumber, OrderByType.Desc)
                        .Select(x => x.DocNumber)
                        .FirstAsync();

                    int serial = 1;
                    if (!string.IsNullOrEmpty(maxNumber) && maxNumber.Length >= todayPrefix.Length + 3)
                    {
                        string serialStr = maxNumber.Substring(todayPrefix.Length, 3);
                        if (int.TryParse(serialStr, out int lastSerial))
                        {
                            serial = lastSerial + 1;
                        }
                    }
                    string newPlanNumber = $"{todayPrefix}{serial:D3}";



                    // 1. 创建生产计划主表记录
                    var productionPlan = new Lwp_ProductionPlan
                    {

                        DocNumber = newPlanNumber,
                        BizType = "生产计划",
                        DocDate = request.DocumentDate,
                        BizNumber = request.SalesOrder,
                        Remark = request.Remarks,
                        TotalQuantity = Convert.ToInt32(request.Items.Sum(i => i.Quantity)),
                        // 其他字段映射
                        BizUser = request.RelatedProject,
                        VersionDesc = request.PlanTheme
                    };
                    
                    // 2. 保存主表记录
                    int planId = await db.Insertable(productionPlan).ExecuteReturnIdentityAsync();
                    productionPlan.Id = planId;
                    
                    // 3. 保存生产物品明细
                    if (request.Items != null && request.Items.Any())
                    {
                        var details = request.Items.Select(item => new ProductionPlanDetail
                        {
                            PlanId = planId,
                            ItemCode = item.ItemCode,
                            ItemName = item.ItemName,
                            Spec = item.Spec,
                            Unit = item.Unit,
                            ItemCategory = item.ItemCategory,
                            ItemClass = item.ItemClass,
                            Brand = item.Brand,
                            Quantity = item.Quantity,
                            DetailDate = item.DetailDate,
                            MainUnitQuantity = item.MainUnitQuantity,
                            Remark = item.Remark
                        }).ToList();
                        
                        await db.Insertable(details).ExecuteCommandAsync();
                    }
                    
                    // 4. 保存附件信息
                    if (request.Attachments != null && request.Attachments.Any())
                    {
                        var attachments = request.Attachments.Select(attach => new ProductionPlanAttachment
                        {
                            PlanId = planId,
                            FileName = attach.FileName,
                            FilePath = attach.FilePath,
                            FileSize = attach.FileSize,
                            FileType = attach.FileType,
                            UploadTime = attach.UploadTime
                        }).ToList();
                        
                        await db.Insertable(attachments).ExecuteCommandAsync();
                    }
                    
                    scope.Complete();
                    
                    result.Success = true;
                    result.Code = 200;
                    result.Message = "生产计划添加成功";
                    result.Data = planId;
                }
            }
            catch (Exception ex)
            {
                result.Success = false;
                result.Code = 500;
                result.Message = "生产计划添加失败";
                result.Error = ex.Message;
            }
            
            return result;
        }

       

    }
} 